<script setup>
import { useRoute } from 'vue-router';
import router from "@/router/index.js";
import {
  deleteAfterSale,
  getDeliveryCompany,
  getOrderDetails,
  sendLogisticsInfo,
  withdrawalApplication
} from "@/api/afterSale.js";
import {getOrderLogistics} from "@/api/order.js";
const route = useRoute();
import { useI18n} from 'vue-i18n';
const { t } = useI18n();
import { showToast } from 'vant';
import useSettingStore from '@/store/modules/setting'


const serviceType = ref('a')
const edit = ref(false)
const orderId = ref(route.query.id) // 订单ID
/*1:提交申请
2:平台审核通过
3:货物已寄回
4:商家同意退款
5:退款成功*/
const stepsData = ref([
  {
    type: 1,
    title: t('afterSale.submitAnOrder'),
    description: '',
  },
  {
    type: 2,
    title: t('afterSale.platformApproval'),
    description: '',
  },
  {
    type: 3,
    title: t('afterSale.returnGoods'),
    description: '',
  },
  {
    type: 4,
    title: t('afterSale.merchantAgreesToRefund'),
    description: '',
  },
  {
    type: 5,
    title: t('afterSale.refundSuccessful'),
    description: '',
  },
]);


const rules = ref({
  deliverySn: [{
    required: true,
    message: t('afterSale.enterTheTrackingNumberTip'),
    trigger: 'change',
  }],
  shipperCode: [{
    required: true,
    message: t('afterSale.selectALogisticsCompanyTip'),
    trigger: 'change',
  }],
})

// 获取订单详情
const explainImgList = ref([]) // 原因图片列表
const logs = ref([])
const remainingTime = ref('');
const orderDetail = ref({
  logs: []
}) // 订单详情数据
async function getDetailInfo(load) {
  getOrderDetails(orderId.value).then((res) => {
    orderDetail.value = res.data;
    formData.value.id = orderDetail.value.id
    explainImgList.value = orderDetail.value.explainImg ? orderDetail.value.explainImg.split(',') : [];
    const {state} = res.data
    // 获取物流信息
    if (state === 2) {
      getLogisticsInformation()
    }
  }).catch(() => {
  })
}

// 获取订单物流信息
const logisticsInfo = ref({})

function getLogisticsInformation() {
  getOrderLogistics(orderDetail.value.deliverySn).then((res) => {
    logisticsInfo.value = res.data;
  }).catch(() => {
  })
}

// 修改申请
function amendmentApplication() {
  edit.value = true
}

// 取消申请弹窗
const openValue = ref(false)
const cancelLoading = ref(false) // 取消申请按钮
function showCancelApplication() {
  openValue.value = true
}

function clickCancelApplication(id) {
  cancelLoading.value = true
  withdrawalApplication(id).then(() => {
    showToast(t('afterSale.cancelSuccessfully'))
    router.push({path: '/afterSale'})
  }).catch(() => {
    showToast(t('afterSale.cancellationFailure'))
  })
}

// 删除记录弹窗申请弹窗
const openDel = ref(false)
const delLoading = ref(false)

function closeDel() {
  openDel.value = false
}

function showCancelDel() {
  openDel.value = true
}

function clickDelAfterSale() {
  delLoading.value = true
  deleteAfterSale(orderDetail.value.id).then(() => {
    showToast(t('afterSale.successfullyDeleted'))
    router.push({path: '/afterSale'})
  }).catch(() => {
    showToast(t('afterSale.deletionFailure'))
  })
}
const deliveryName = {
  text: 'label',
  value: 'value',
  children: null,
};
// 填写物流弹窗
const openMaterialFlow = ref(false)

const formData = ref({}) // 物流参数

function closeMaterialFlow() {
  openMaterialFlow.value = false
}

function showMaterialFlow() {
  openMaterialFlow.value = true
}

// 确认发货
const materialLoading = ref(false)
const formRef = ref(null)
function fillInLogisticsInfo() {
  formRef.value.validate().then(() => {
    materialLoading.value = true
    sendLogisticsInfo(formData.value).then(() => {
      showToast(t('afterSale.deliverySuccess'))
      openMaterialFlow.value = false
      getDetailInfo(true)
    }).catch(() => {
      showToast(t('afterSale.deliveryFailure'))
    })
  }).catch(error => {
    materialLoading.value = false
  });
}

// 获取物流公司列表
const deliveryList = ref([]) // 物流公司列表
function getDeliveryList() {
  getDeliveryCompany().then((res) => {
    deliveryList.value = res.data
    formData.value.deliveryName = deliveryList.value[0].label
    formData.value.shipperCode = deliveryList.value[0].value
  })
}

// 选择物流公司
const showDelivery = ref(false)
function changeDelivery(data) {
  const { selectedValues } = data
  showDelivery.value = false
  let matchedDelivery = deliveryList.value.find(item => item.value === selectedValues[0]);
  if (matchedDelivery) {
    formData.value.deliveryName = matchedDelivery.label;
  }
}

onMounted(() => {
  getDetailInfo(true)
  getDeliveryList()
})
</script>

<template>
  <div class="p-center">
    <div class="main-con" id="loading">
      <div class="order-detail">
        <div class="top-state">
          <div class="top-l">
            <div class="order-state">
              <span v-if="orderDetail.state === 0">{{ t('afterSale.waitingForPlatformReview') }}</span>
              <span v-if="orderDetail.state === 1">{{ t('afterSale.returnGoodsAsSoonAsPossible') }}</span>
              <span v-if="orderDetail.state === 2">{{ t('afterSale.merchantReceivingGoods') }}</span>
              <span v-if="orderDetail.state === 3">{{ t('afterSale.refundSuccessful') }}</span>
              <span v-if="orderDetail.state === 4">{{ t('afterSale.refundSuccessful') }}</span>
            </div>
            <div class="order-id">{{ t('afterSale.orderNumber') }}：{{ orderDetail.orderCode }}</div>
          </div>
        </div>
        <div class="order-detail-box">
          <div class="receipt-info" v-if="orderDetail.state === 1">
            <h4>{{ t('afterSale.returnAddress') }}</h4>
            <div class="receipt-box">
              <div class="receipt-userName">{{ orderDetail.consignee }}</div>
              <div class="receipt-address">
                <div class="receipt-address-detail">{{ orderDetail.address }}</div>
                <div class="receipt-address-contact">{{ orderDetail.phoneNumber }}，{{t('orderDetail.postcode')}}：{{orderDetail.postCode}}</div>
              </div>
              <div class="receipt-country">{{orderDetail.country}}</div>
            </div>
          </div>
          <div class="logistics" v-if="orderDetail.state === 1 || orderDetail.state === 2 || orderDetail.state === 3">
            <h4>{{ t('afterSale.returnLogisticsInfo') }}</h4>
            <div class="logistics-box" v-if="orderDetail.state !== 1">
              <div class="logistics-tit">
                <div class="logistics-companiess">
                  {{ t('afterSale.logisticsCompany') }}：<b>{{ orderDetail.deliveryName }}</b></div>
                <div class="tracking-number">{{ t('afterSale.waybillNumber') }}：<b>{{ orderDetail.deliverySn }}</b>
                </div>
              </div>
              <div class="timeline">
                <ul class="time-axis" :class="{ 'is-done': index === 0 }" v-for="(item,index) in logisticsInfo" :key="index">
                  <li>{{ item.key_stage }}</li>
                  <li>{{ item.time_iso }}</li>
                </ul>
              </div>
            </div>
            <div v-else class="ant-btn materialFlow-btn">
              <van-button class="add-btn" @click="showMaterialFlow">
                {{ t('afterSale.fillInLogisticsInfo') }}
              </van-button>
            </div>
          </div>
          <div class="listing">
            <div class="listing-top">
              <div class="listing-left">
                <div class="listing-tit">{{ t('afterSale.commodityList') }}</div>
<!--                <div class="listing-num">{{ t('afterSale.quantity') }}</div>-->
              </div>
<!--              <div class="listing-total">{{ t('afterSale.subtotal') }}</div>-->
            </div>
            <div class="list-product">
              <div class="product-item" v-for="(item, index) of orderDetail.details">
                <div class="product-left">
<!--                  <a-checkbox v-if="edit" v-model:checked="checked"></a-checkbox>-->
                  <div class="product-img">
                    <img :src="item.image" alt="">
                    <div class="product-info">
                      <div class="product-tit-sku">
                        <div class="product-tit">{{ item.productName }}</div>
<!--                        <div class="product-sku">{{ item.sku }}</div>-->
                      </div>
                      <div class="amount-quantity">
                        <div class="product-amount">$ {{ item.price }}</div>
                        <div class="product-num">x{{ item.num }}</div>
                      </div>
                    </div>
                  </div>
                </div>
<!--                <div class="product-total">$ {{ item.price * item.num }}</div>-->
              </div>
            </div>
          </div>
        </div>
        <div class="afterSales-Info">
<!--          <h4>{{ t('afterSale.afterSalesInfo') }}</h4>-->
          <div class="info-box">
            <div class="info-item">
              <div class="info-tit">{{ t('afterSale.totalRefund') }}：</div>
              <div class="info-value">${{ orderDetail.refundAmount }}</div>
            </div>
            <div class="info-item">
              <div class="info-tit">{{ t('afterSale.totalMerchandise') }}：</div>
              <div class="info-value">${{ orderDetail.totalPrice }}</div>
            </div>
            <div class="info-item">
              <div class="info-tit">{{ t('commodity.toOffset') }}：</div>
              <div class="info-value">${{ orderDetail.integralDeduct }}</div>
            </div>
            <div class="info-item">
              <div class="info-tit">{{ t('afterSale.freight') }}：</div>
              <div class="info-value">${{ orderDetail.totalPostage ? orderDetail.totalPostage : 0 }}</div>
            </div>
          </div>
          <div class="info-box">
            <div class="info-item">
              <div class="info-tit">{{ t('afterSale.commission') }}：</div>
              <div class="info-value">${{ orderDetail.taxation }}</div>
            </div>
            <div class="info-item">
              <div class="info-tit">{{ t('afterSale.favorable') }}：</div>
              <div class="info-value">${{ orderDetail.couponPrice }}</div>
            </div>
          </div>
          <h4 class="afterSalesInfo-tit">{{t('afterSale.afterSalesInfo')}}</h4>
          <div class="info-box">
            <div class="info-item">
              <div class="info-tit">{{ t('afterSale.afterSaleNumber') }}：</div>
              <div class="info-value">
                {{ orderDetail.afterSalesCode }}
              </div>
            </div>
<!--            <div class="info-item">-->
<!--              <div class="info-tit">{{ t('afterSale.applicationTime') }}：</div>-->
<!--              <div class="info-value">-->
<!--                {{ orderDetail.afterSalesCode }}-->
<!--              </div>-->
<!--            </div>-->
            <div class="info-item">
              <div class="info-tit">{{ t('afterSale.serviceType') }}：</div>
              <div class="info-value">
                {{ orderDetail.serviceType === 1 ? t('afterSale.returnGoodsRefund') : t('afterSale.refundOnly') }}
              </div>
            </div>
            <div class="info-item explain">
              <div class="info-tit">{{ t('afterSale.cause') }}：</div>
              <div class="info-value">{{ orderDetail.reasons }}</div>
            </div>
          </div>
          <div class="info-box">
            <div class="info-item explain">
              <div class="info-tit">{{ t('afterSale.applicationInstructions') }}：</div>
              <div class="info-value">{{ orderDetail.explains }}</div>
            </div>
          </div>
          <div class="info-box">
            <div class="info-item">
              <div class="info-tit">{{ t('afterSale.photoCertificate') }}：</div>
              <div class="info-value">
                <img v-for="(item, index) of explainImgList" :src="item" :key="index">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="top-r ant-btn after-btn-box">
     <div class="btn-center">
       <van-button @click="showCancelDel"
                   v-if="orderDetail.state === 4 || orderDetail.state === 3 || orderDetail.state === -2 || orderDetail.state === -1"
                   class="del-btn s-btn">{{ t('afterSale.deleteRecord') }}
       </van-button>
       <!--            <van-button class="del-btn line-btn" @click="amendmentApplication">修改申请</van-button>-->
       <van-button class="del-btn s-btn"
                   v-if="orderDetail.state === 0 || orderDetail.state === 1 || orderDetail.state === 2"
                   @click="showCancelApplication">{{ t('afterSale.withdrawalOfApplication') }}
       </van-button>
     </div>
    </div>
    <!--    删除订单弹窗-->
    <van-popup v-model:show="openDel" :style="{ padding: '16px', width: '85%' }">
      <div class="popup-box">
        <h3>{{t('afterSale.whetherToDelete')}}</h3>
        <div class="btn-box">
          <van-button class="add-btn s-btn" @click="openDel = false">{{t('order.cancel')}}</van-button>
          <van-button :loading="delLoading" class="s-btn" @click="clickDelAfterSale()">{{t('order.affirm')}}</van-button>
        </div>
      </div>
    </van-popup>
    <!--    撤销申请弹窗-->
    <van-popup v-model:show="openValue" :style="{ padding: '16px', width: '85%' }">
      <div class="popup-box">
        <h3>{{t('afterSale.whetherToCancelOrder')}}</h3>
        <div class="btn-box">
          <van-button class="add-btn s-btn" @click="openValue = false">{{t('order.cancel')}}</van-button>
          <van-button :loading="cancelLoading" class="s-btn" @click="clickCancelApplication(orderDetail.id)">{{t('order.affirm')}}</van-button>
        </div>
      </div>
    </van-popup>
    <!--    录入物流弹窗-->
    <van-popup v-model:show="openMaterialFlow" :style="{ padding: '16px', width: '85%' }">
      <div class="popup-box">
        <h3>{{t('afterSale.inputLogistics')}}</h3>
        <van-form
            ref="formRef"
            validate-trigger="['onSubmit']"
        >
          <c-input
              name="lastName"
              v-model:value="formData.deliverySn"
              :placeholder="`${t('afterSale.logisticsTrackingNumber')}*`"
              :rules="[
                  { required: true, message: t('afterSale.enterTheTrackingNumberTip')}
              ]"
          />
          <div class="select-box">
            <van-field
                v-model="formData.deliveryName"
                is-link
                readonly
                :placeholder="!formData.deliveryName ? `${t('afterSale.selectALogisticsCompanyTip')}` : ''"
                @click="showDelivery = true"
            />
          </div>
          <van-popup v-model:show="showDelivery" round position="center" :style="{ padding: '16px', width: '85%' }">
            <van-picker
                :columns="deliveryList"
                :columns-field-names="deliveryName"
                @cancel="showDelivery = false"
                @confirm="changeDelivery"
            />
          </van-popup>
        </van-form>
        <div class="btn-box">
          <van-button class="add-btn s-btn" @click="openMaterialFlow = false">{{t('order.cancel')}}</van-button>
          <van-button :loading="materialLoading" class="s-btn"  @click="fillInLogisticsInfo(orderDetail.id)">{{t('order.affirm')}}</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style scoped lang="scss">
.p-center {
  padding: 16px 16px 100px 16px;
  .main-con {
    .order-detail {
      .top-state {
        margin-bottom: 15px;
        display: flex;
        justify-content: space-between;

        .top-l {
          .order-state {
            font-weight: 600;
            font-size: 16px;
            color: #262626;
            margin-bottom: 4px;
          }

          .order-id {
            font-size: 12px;
            color: #8C8C8C;
            font-weight: 400;
          }
        }
        .top-r {
          display: flex;
          .del-btn {
            margin-left: 10px;
          }
        }

        .del-btn {
          width: 156px;
          height: 44px;
          border-radius: 2px 2px 2px 2px;
        }
      }

      .listing {
        margin-top: 0px;
        margin-bottom: 15px;

        .listing-top {
          display: flex;
          font-weight: 600;
          font-size: 16px;
          color: #262626;
          border-bottom: 1px solid #E5E5E5;
          padding-bottom: 10px;
          justify-content: space-between;

          .listing-left {
            display: flex;

            .listing-tit {
            }
          }

          .listing-total {
            flex: 1;
            text-align: right;
          }

          .listing-tit {
          }
        }

        .list-product {
          .product-item {
            width: 100%;
            margin-bottom: 16px;
            padding-bottom: 16px;
            border-bottom: 1px solid #E5E5E5;
            :deep(.product-left) {
              display: flex;
              .product-img {
                width: 100%;
                display: flex;
                margin-left: 12px;

                img {
                  width: 98px;
                  height: 110px;
                  margin-right: 12px;
                }
              }

              .product-num {
              }

              .product-amount {
                flex: 1;
                display: flex;
                flex-flow: column-reverse;
              }

              .product-info {
                color: #262626;
                font-size: 14px;
                display: flex;
                flex-flow: column;
                flex: 1;
                .amount-quantity {
                  display: flex;
                  justify-content: space-between;
                  margin-top: 15px;
                  .product-num {
                    font-size: 12px;
                    color: #8C8C8C;
                  }
                }
                .product-tit {
                  font-weight: 600;
                  margin: 15px 0;
                }

                .product-sku {
                  font-weight: 400;
                }

                .product-amount {
                  color: #666666;
                }
              }
            }
          }
        }
      }

      .materialFlow-btn {
        display: flex;
        justify-content: center;

        button {
          width: 148px;
          height: 44px;
          margin: 0 auto;
        }
      }

      .logistics {
        margin-top: 30px;

        h4 {
          font-size: 16px;
        }

        .logistics-box {
          border-radius: 2px;
          border: 1px solid #8C8C8C;
          padding: 16px;
          margin-bottom: 10px;
          .logistics-tit {
            border-bottom: 1px solid #E5E5E5;
            margin-bottom: 15px;
            padding-bottom: 10px;
            color: #8C8C8C;
            font-size: 14px;
            font-weight: 400;

            b {
              color: #262626;
              font-weight: 400;
            }

            .logistics-companies {
              margin-right: 24px;
            }
          }

          .timeline {
            .circular {
              border-radius: 50%;
              padding: 0;
              border: none;
              width: 10px;
              height: 10px;

              i {
                width: 10px;
                height: 10px;
                display: block;
                background: #BFBFBF;
                border-radius: 50%;
              }
            }

            .active {
              width: 16px;
              height: 16px;
              padding: 2px;
              box-sizing: border-box;
              border: 1px solid #262626;

              i {
                background: #262626;
              }
            }

            p {
              font-weight: 400;
              font-size: 14px;
              color: #262626;
            }

            .logistical-time {
              color: #8C8C8C;
            }
          }
        }
      }

      .receipt-info {
        margin: 20px 0 15px 0;
        h4 {
          font-size: 14px;
        }
        .receipt-box {
          border-radius: 2px;
          border: 1px solid #8C8C8C;
          margin-top: 12px;
          padding: 16px;
          font-size: 14px;
          .receipt-userName {
            font-weight: 600;
            color: #262626;
            margin-bottom: 10px;
          }
          .receipt-address {
            font-size: 12px;
            color: #262626;
            font-weight: 400;
            margin-bottom: 10px;
            .receipt-address-detail {
              margin-bottom: 5px;
              font-size: 12px;
            }
          }

          .receipt-country {
            flex: 1;
            color: #262626;
            font-weight: 400;
            font-size: 12px;
          }
        }
      }

      .price-breakdown {
        background: #FAFAFA;
        border-radius: 2px;
        padding: 16px;
        font-weight: 400;
        font-size: 14px;
        color: #262626;
        .flex-box {
          margin-bottom: 8px;
        }
        .amount-due {
          padding-top: 24px;
          margin-top: 16px;
          border-top: #E5E5E5 solid 1px;
        }
      }
      .form-box {
        margin-top: 32px;

        .type-service {
          .type-item {
            width: 117px;
            height: 44px;
            line-height: 44px;
            text-align: center;
            border-radius: 2px;
            border: 1px solid #8C8C8C;
            font-weight: 400;
            font-size: 14px;
            color: #8C8C8C;
            cursor: pointer;
            margin-right: 16px;
          }

          .type-item:hover, .active {
            border: 1px solid #262626;
            color: #262626;
          }
        }

        .clearfix {
          margin-bottom: 32px;
          .number-uploads {
            font-weight: 400;
            font-size: 12px;
            color: #262626;
            b {
              font-weight: 400;
              color: #E85A2B;
            }
          }
        }
      }

      .submit-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: #FAFAFA;
        border-radius: 2px;
        padding: 16px;
        .ant-btn {
          display: flex;
          align-items: center;
          .btn-item {
            margin-left: 15px;
            button {
              width: 156px;
              height: 44px;
              justify-content: center;
            }
          }
        }
      }
    }
  }
}
.afterSales-Info {
  h4 {
    margin-bottom: 20px;
  }
  .afterSalesInfo-tit {
    font-size: 14px;
    margin: 15px 0;
    border-top: 8px solid #F8F8F8;
    padding-top: 16px;
  }
  .info-box {
    .info-item {
      display: flex;
      color: #262626;
      font-size: 14px;
      margin-bottom: 15px;
      justify-content: space-between;
      .info-tit {
        text-align: right;
      }

      .info-value {
        font-weight: 500;
        img {
          width: 50px;
          height: 50px;
          margin: 5px;
        }
      }
    }

    .explain {
    }
  }
}
.delete-box {
  h3 {
    text-align: center;
  }

  .delete-order {
    .btn-box {
      margin-top: 20px;
      display: flex;

      button {
        margin: 5px;
      }
    }
  }

  .ant-btnant-btn {
    display: flex;
    align-items: center;
  }
}
.popup-box {
  width: 100%;
  .select-box {
    border: 1px solid #E5E5E5;
  }
  h3 {
    font-weight: 500;
    font-size: 16px;
    color: #262626;
    text-align: center;
  }
  .btn-box {
    margin-top: 20px;
    display: flex;
    button {
      margin:5px;
      height: 44px;
    }
  }
}
/* 时间轴 */
.time-axis {
  color: #262626;
  position: relative;
  padding-left: 30px;
  list-style: none;
  &:before {
    position: absolute;
    margin-top: 8px;
    left: 4px;
    content: " ";
    height: 9px;
    width: 9px;
    border-radius: 50%;
    background-color: #e8e8e8;
  }
  &:after {
    position: absolute;
    top: 17px;
    left: 7px;
    bottom: -19px;
    content: " ";
    width: 1px;
    border-right: 1px solid #e8e8e8;
  }
  &:not(:first-child) {
    padding-top: 8px;
  }
  &:last-child {
    &:after {
      display: none;
    }
  }
  &.is-done {
    &:after {
      border-color: #BFBFBF;
    }
    &:before {
      background-color: #262626;
      box-shadow: #BFBFBF 0 0 10px;
    }
  }
}
.after-btn-box {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  background: #fff;
  padding: 6px 16px;
  box-sizing: border-box;
  border-top: 1px solid #E5E5E5;
  .btn-center {

  }
}
</style>
